# -*- coding: utf-8 -*-
# @Time        :2025/2/26 14:01
# @Author      :文刀水寿
# @File        : 服务端.py
"""
 @Description :
"""
import socket
import random
import json

HOST = '127.0.0.1'
PORT = 9999


def guess(number):
    target = random.randint(1, 100)
    attempts = 0
    print(f"目标数字：{target}")

    while True:
        try:
            str1 = number.recv(1024).decode()
            if not str1:
                break

            request = json.loads(str1)
            guess = int(request["guess"])
            attempts += 1

            # 范围验证
            if guess < 1 or guess > 100:
                response = {
                    "status": 500,
                    "message": "非法数值范围",
                    "attempts": attempts
                }
                number.send(json.dumps(response).encode())
                continue

            # 游戏逻辑
            if guess == target:
                response = {
                    "status": 200,
                    "message": " 恭喜猜中！",
                    "attempts": attempts
                }
                number.send(json.dumps(response).encode())
                break
            elif guess < target:
                response = {
                    "status": 300,
                    "message": "目标数字更大",
                    "attempts": attempts
                }
            else:
                response = {
                    "status": 400,
                    "message": " 目标数字更小",
                    "attempts": attempts
                }
            number.send(json.dumps(response).encode())

        except (KeyError, ValueError):
            error = {
                "status": 500,
                "message": " 无效请求格式",
                "attempts": attempts
            }
            number.send(json.dumps(error).encode())


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print("服务端已启动，等待连接...")
    while True:
        number, addr = s.accept()
        print(f"客户端 {addr} 已连接!")
        guess(number)
        number.close()
